/**
 * 不完整管道写示例
*/

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

void signal_handler(int signum)
{
    if (SIGPIPE == signum)
    {
        printf("signal is SIGPIPE!\n");
    }
}

int main(void)
{
    int pipe_fds[2];
    if (pipe(pipe_fds) < 0)
    {
        perror("pipe error: ");
        exit(EXIT_FAILURE);
    }

    pid_t pid = fork();
    if (0 > pid)
    {
        perror("fork error: ");
        exit(EXIT_FAILURE);
    }
    else if (0 == pid)
    {
        close(pipe_fds[0]);
        close(pipe_fds[1]);
    }
    else
    {
        close(pipe_fds[0]);

        signal(SIGPIPE, signal_handler);

        sleep(5); //睡眠，保证子进程先执行，读管道关闭

        if (write(pipe_fds[1], "123", 3) < 0)
        {
            fprintf(stderr, "%s\t%s\n", strerror(errno),
                    errno == EPIPE ? "EPIPE" : "unknown");
        }

        wait(0);
    }

    return 0;
}